import { useState, useEffect } from 'react';
import { Bell, Wifi, WifiOff, Smartphone } from 'lucide-react';
import { EnhancedNotificationService } from '../services/enhancedNotification';
import PWANotificationService from '../services/pwaNotificationService';

interface NotificationManagerProps {
  onClose?: () => void;
}

export default function EnhancedNotificationManager({ onClose }: NotificationManagerProps) {
  const [activeTab, setActiveTab] = useState<'pwa' | 'test'>('pwa');
  const [notificationService] = useState(() => EnhancedNotificationService.getInstance());
  const [pwaService] = useState(() => PWANotificationService.getInstance());
  const [permission, setPermission] = useState<NotificationPermission>('default');
  const [testNotificationType, setTestNotificationType] = useState<'simple' | 'template' | 'batch' | 'pwa'>('simple');
  const [pwaStatus, setPwaStatus] = useState({
    supported: false,
    subscribed: false,
    permission: 'default' as NotificationPermission
  });

  useEffect(() => {
    // 检查通知权限
    if ('Notification' in window) {
      setPermission(Notification.permission);
    }

    // 检查PWA推送通知状态
    checkPwaStatus();
  }, [pwaService]);

  const checkPwaStatus = async () => {
    console.log('🔍 检查PWA推送通知状态...');
    try {
      const status = await pwaService.getSubscriptionStatus();
      console.log('📊 PWA状态:', status);
      setPwaStatus(status);
    } catch (error) {
      console.error('❌ 检查PWA状态失败:', error);
    }
  };





  const handleTestSimpleNotification = async () => {
    await notificationService.showEnhancedNotification({
      title: '🔔 测试通知',
      body: '这是一个简单的测试通知',
      priority: 'normal',
      category: 'system',
      sound: true,
      actions: [
        { action: 'ok', title: '好的' },
        { action: 'dismiss', title: '忽略' }
      ],
      onClick: () => {
        console.log('测试通知被点击');
      }
    });
  };

  const handleTestTemplateNotification = async () => {
    await notificationService.showTemplateNotification('task-reminder', {
      taskTitle: '完成项目文档',
      dueTime: '30分钟'
    });
  };

  const handleTestBatchNotifications = async () => {
    const notifications = [
      {
        title: '📋 任务提醒 1',
        body: '完成设计稿审核',
        category: 'reminder' as const,
        priority: 'normal' as const
      },
      {
        title: '📋 任务提醒 2', 
        body: '准备周会材料',
        category: 'reminder' as const,
        priority: 'normal' as const
      },
      {
        title: '⚠️ 紧急任务',
        body: '修复生产环境bug',
        category: 'deadline' as const,
        priority: 'urgent' as const
      }
    ];

    await notificationService.showBatchNotifications(notifications, {
      groupByCategory: true,
      delay: 500
    });
  };

  const handleSubscribePwa = async () => {
    console.log('🔔 开始订阅PWA推送通知...');
    try {
      const subscription = await pwaService.subscribeToPushNotifications();
      console.log('📱 PWA订阅结果:', subscription);
      if (subscription) {
        await checkPwaStatus();
        console.log('✅ PWA推送通知订阅成功');
      } else {
        console.warn('❌ PWA推送通知订阅失败');
      }
    } catch (error) {
      console.error('❌ PWA推送通知订阅出错:', error);
    }
  };

  const handleUnsubscribePwa = async () => {
    const success = await pwaService.unsubscribeFromPushNotifications();
    if (success) {
      await checkPwaStatus();
    }
  };

  const handleTestPwaNotification = async () => {
    await pwaService.testPushNotification();
  };

  const handleDebugPushManager = async () => {
    console.log('🔍 调试推送管理器...');
    
    // 检查基本支持
    console.log('📋 推送支持检查:', {
      'Service Worker支持': 'serviceWorker' in navigator,
      '推送管理器支持': 'PushManager' in window,
      '通知支持': 'Notification' in window,
      '当前权限': Notification.permission
    });

    // 检查Service Worker状态
    if ('serviceWorker' in navigator) {
      const registration = await navigator.serviceWorker.ready;
      console.log('🔧 Service Worker状态:', {
        '作用域': registration.scope,
        '激活状态': registration.active?.state,
        '推送管理器': !!registration.pushManager
      });

      // 尝试简单的推送管理器操作
      if (registration.pushManager) {
        try {
          const permissionState = await registration.pushManager.permissionState({
            userVisibleOnly: true
          });
          console.log('🔔 推送权限状态:', permissionState);
        } catch (error) {
          console.error('❌ 检查推送权限失败:', error);
        }
      }
    }
  };





  const renderPwaTab = () => (
    <div className="space-y-6">
      {/* PWA功能说明 */}
      <div className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg">
        <h3 className="font-semibold text-blue-900 mb-2">PWA推送通知功能</h3>
        <p className="text-sm text-blue-700 mb-3">
          PWA（渐进式Web应用）推送通知可以在应用关闭时仍然接收任务提醒，提供类似原生应用的体验。
        </p>
        <div className="text-xs text-blue-600 space-y-1">
          <p>✅ 后台推送通知</p>
          <p>✅ 离线消息缓存</p>
          <p>✅ 系统级通知显示</p>
        </div>
      </div>

      {/* PWA推送通知设置 */}
      <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
        <div className="flex items-start space-x-3">
          {pwaStatus.subscribed ? (
            <Wifi className="w-5 h-5 text-green-600 mt-0.5" />
          ) : (
            <WifiOff className="w-5 h-5 text-gray-400 mt-0.5" />
          )}
          <div className="flex-1">
            <div className="flex items-center justify-between">
              <h3 className="font-medium text-blue-900">PWA推送通知</h3>
              <span className={`text-xs px-2 py-1 rounded-full ${
                pwaStatus.subscribed 
                  ? 'bg-green-100 text-green-700' 
                  : 'bg-gray-100 text-gray-600'
              }`}>
                {pwaStatus.subscribed ? '已启用' : '未启用'}
              </span>
            </div>
            <p className="text-sm text-blue-700 mt-1">
              {pwaStatus.supported 
                ? (window.location.protocol === 'https:' || window.location.hostname === 'localhost'
                    ? '支持后台推送通知，即使应用未打开也能接收提醒'
                    : '⚠️ 推送通知需要HTTPS环境，当前为HTTP环境可能无法正常工作')
                : '您的浏览器不支持PWA推送通知功能'
              }
            </p>
            {pwaStatus.supported && (
              <div className="mt-3 flex space-x-2">
                {!pwaStatus.subscribed ? (
                  <button
                    onClick={handleSubscribePwa}
                    disabled={permission !== 'granted'}
                    className="px-3 py-1 text-xs bg-blue-600 text-white rounded hover:bg-blue-700 disabled:bg-gray-300"
                  >
                    启用推送通知
                  </button>
                ) : (
                  <button
                    onClick={handleUnsubscribePwa}
                    className="px-3 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700"
                  >
                    禁用推送通知
                  </button>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 本地开发环境提示 */}
      {(window.location.hostname === 'localhost' && window.location.protocol === 'http:') && (
        <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
          <div className="flex items-start space-x-3">
            <div className="text-yellow-600 mt-0.5">⚠️</div>
            <div>
              <h3 className="font-medium text-yellow-900">本地开发环境限制</h3>
              <p className="text-sm text-yellow-700 mt-1">
                PWA推送通知在本地HTTP环境下可能无法正常工作。
              </p>
              <div className="mt-2 text-xs text-yellow-700">
                <p><strong>建议的解决方案：</strong></p>
                <ul className="list-disc list-inside mt-1 space-y-1">
                  <li>部署到HTTPS服务器进行测试</li>
                  <li>使用 ngrok 创建HTTPS隧道</li>
                  <li>配置本地HTTPS开发环境</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* PWA安装提示 */}
      <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
        <div className="flex items-start space-x-3">
          <Smartphone className="w-5 h-5 text-blue-600 mt-0.5" />
          <div>
            <h3 className="font-medium text-blue-900">PWA应用模式</h3>
            <p className="text-sm text-blue-700 mt-1">
              将应用安装到设备可获得更好的通知体验，包括后台通知和离线功能。
            </p>
            <button className="mt-2 text-xs text-blue-600 hover:text-blue-800 underline">
              了解如何安装
            </button>
          </div>
        </div>
      </div>

      {/* 高级设置预览 */}
      <div className="p-4 bg-gray-50 rounded-lg">
        <h3 className="font-medium text-gray-900 mb-3">高级功能预览</h3>
        <div className="space-y-2 text-sm text-gray-600">
          <div className="flex items-center justify-between">
            <span>智能提醒时间</span>
            <span className="text-green-600">✅ 已启用</span>
          </div>
          <div className="flex items-center justify-between">
            <span>批量通知管理</span>
            <span className="text-green-600">✅ 已启用</span>
          </div>
          <div className="flex items-center justify-between">
            <span>通知模板系统</span>
            <span className="text-green-600">✅ 已启用</span>
          </div>
          <div className="flex items-center justify-between">
            <span>地理位置提醒</span>
            <span className="text-yellow-600">🔄 开发中</span>
          </div>
        </div>
      </div>
    </div>
  );



  const renderTestTab = () => (
    <div className="space-y-6">
      {/* 测试类型选择 */}
      <div className="p-4 bg-gray-50 rounded-lg">
        <h3 className="font-medium text-gray-900 mb-3">测试类型</h3>
        <div className="flex space-x-2">
          {[
            { key: 'simple', label: '简单通知' },
            { key: 'template', label: '模板通知' },
            { key: 'batch', label: '批量通知' },
            { key: 'pwa', label: 'PWA推送' }
          ].map((type) => (
            <button
              key={type.key}
              onClick={() => setTestNotificationType(type.key as any)}
              className={`px-3 py-1 text-sm rounded ${
                testNotificationType === type.key
                  ? 'bg-blue-600 text-white'
                  : 'bg-white text-gray-600 border'
              }`}
            >
              {type.label}
            </button>
          ))}
        </div>
      </div>

      {/* 测试按钮 */}
      <div className="space-y-3">
        {testNotificationType === 'simple' && (
          <button
            onClick={handleTestSimpleNotification}
            disabled={permission !== 'granted'}
            className="w-full p-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed"
          >
            发送简单测试通知
          </button>
        )}

        {testNotificationType === 'template' && (
          <button
            onClick={handleTestTemplateNotification}
            disabled={permission !== 'granted'}
            className="w-full p-3 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:bg-gray-300 disabled:cursor-not-allowed"
          >
            发送模板测试通知
          </button>
        )}

        {testNotificationType === 'batch' && (
          <button
            onClick={handleTestBatchNotifications}
            disabled={permission !== 'granted'}
            className="w-full p-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:bg-gray-300 disabled:cursor-not-allowed"
          >
            发送批量测试通知
          </button>
        )}

        {testNotificationType === 'pwa' && (
          <>
            <button
              onClick={handleTestPwaNotification}
              disabled={!pwaStatus.subscribed}
              className="w-full p-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:bg-gray-300 disabled:cursor-not-allowed"
            >
              发送PWA推送通知
            </button>
            <button
              onClick={handleDebugPushManager}
              className="w-full p-3 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700"
            >
              调试推送管理器
            </button>
          </>
        )}
      </div>

      {permission !== 'granted' && testNotificationType !== 'pwa' && (
        <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
          <p className="text-sm text-yellow-700">
            请先在设置页面中授权通知权限，然后再进行测试。
          </p>
        </div>
      )}

      {testNotificationType === 'pwa' && !pwaStatus.subscribed && (
        <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
          <p className="text-sm text-blue-700">
            请先在设置页面中启用PWA推送通知，然后再进行测试。
          </p>
        </div>
      )}

      {/* 测试说明 */}
      <div className="p-4 bg-gray-50 rounded-lg">
        <h3 className="font-medium text-gray-900 mb-2">测试说明</h3>
        <div className="text-sm text-gray-600 space-y-1">
          <p><strong>简单通知：</strong>基础的增强通知，包含动作按钮</p>
          <p><strong>模板通知：</strong>使用预定义模板的任务提醒通知</p>
          <p><strong>批量通知：</strong>同时发送多个通知，自动分组管理</p>
          <p><strong>PWA推送：</strong>通过Service Worker发送的后台推送通知</p>
        </div>
      </div>
    </div>
  );

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[60]">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b">
          <h2 className="text-xl font-semibold text-gray-900">PWA推送通知配置</h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600"
          >
            ✕
          </button>
        </div>

        {/* 标签页导航 */}
        <div className="flex border-b">
          {[
            { key: 'pwa', label: 'PWA推送', icon: Wifi },
            { key: 'test', label: '测试', icon: Bell }
          ].map(({ key, label, icon: Icon }) => (
            <button
              key={key}
              onClick={() => setActiveTab(key as any)}
              className={`flex items-center space-x-2 px-6 py-3 text-sm font-medium border-b-2 ${
                activeTab === key
                  ? 'border-blue-600 text-blue-600'
                  : 'border-transparent text-gray-600 hover:text-gray-900'
              }`}
            >
              <Icon className="w-4 h-4" />
              <span>{label}</span>
            </button>
          ))}
        </div>

        {/* 内容区域 */}
        <div className="p-6 overflow-y-auto max-h-[60vh]">
          {activeTab === 'pwa' && renderPwaTab()}
          {activeTab === 'test' && renderTestTab()}
        </div>
      </div>
    </div>
  );
}
